import pymysql
from pymysql.cursors import Cursor

from my_logging import GetLogger

from .config import SQL_DATABASE_CONFIG

logger = GetLogger('sql_Cursor')


class _cursorWithLog_(Cursor):
    def execute(self, query: str, args: object = None) -> int:
        logger.debug(f'query = "{query}"')
        effected_row = super().execute(query, args)
        logger.debug(f'effected_row = {effected_row}')

        return effected_row


class MyCursor():
    def __init__(self, need_to_commit : bool = False) -> None:
        self.connect = pymysql.connect(**SQL_DATABASE_CONFIG)
        self.cursor = self.connect.cursor(_cursorWithLog_)
        self.need_to_commit = need_to_commit

    def __enter__(self):
        return self.cursor


    def __exit__(self, *exc_info):
        del exc_info
        self.cursor.close()
        if self.need_to_commit:
            self.connect.commit()
        self.connect.close()
